<?php

class GroupController extends AdminController {

    public function actionList() {

        $model = new site_administrator_group('search');

        $this->render('list', array('model' => $model));
    }

    public function actionCreate() {

        $modelGroup = new site_administrator_group;
        $data = $this->getDataFormatted($this->getData());

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['site_administrator_group'])) {
            $modelGroup->attributes = $_POST['site_administrator_group'];
            $trans = Yii::app()->db->beginTransaction();

            if (isset($_POST['aksesparent'])) {
                if ($modelGroup->save()) {
                    try {
                        if (isset($_POST['aksesparent'])) {
                            foreach ($_POST['aksesparent'] as $val => $value) {
                                $modelInsertPrivilege = new site_administrator_privilege;
                                $modelInsertPrivilege->administrator_privilege_administrator_group_id = $modelGroup->administrator_group_id;
                                $modelInsertPrivilege->administrator_privilege_administrator_menu_id = $value;
                                $modelInsertPrivilege->administrator_privilege_action_create = 0;
                                $modelInsertPrivilege->administrator_privilege_action_update = 0;
                                $modelInsertPrivilege->administrator_privilege_action_delete = 0;
                                $modelInsertPrivilege->save();
                            }
                            $modelInsertPrivilege->refresh();

                            if (isset($_POST['akseschild'])) {
                                foreach ($_POST['akseschild'] as $valchild => $valuechild) {
                                    $modelInsertPrivilegeChild = new site_administrator_privilege;
                                    $modelInsertPrivilegeChild->administrator_privilege_administrator_group_id = $modelGroup->administrator_group_id;
                                    $modelInsertPrivilegeChild->administrator_privilege_administrator_menu_id = $valuechild;
                                    $modelInsertPrivilegeChild->administrator_privilege_action_create = (isset($_POST['akseschild_create'][$valchild]) ? '1' : '0');
                                    $modelInsertPrivilegeChild->administrator_privilege_action_update = (isset($_POST['akseschild_update'][$valchild]) ? '1' : '0');
                                    $modelInsertPrivilegeChild->administrator_privilege_action_delete = (isset($_POST['akseschild_delete'][$valchild]) ? '1' : '0');

                                    $modelInsertPrivilegeChild->save();
                                }
                                $modelInsertPrivilegeChild->refresh();
                            }
                        }

                        $trans->commit();
                        $this->redirect(array('list'));
                    } catch (Exception $e) {
                        $trans->rollBack();
                    }
                }
            } else {
                Yii::app()->user->setFlash('pesan', "Anda belum memilih hak akses menu");
            }
        }

        $this->render('create', array(
            'model' => $modelGroup,
            'data' => $data,
        ));
    }

    public function actionUpdate($id) {

//        echo "<pre>";
//print_r($_POST);
//echo "</pre>";
        $modelGroup = $this->loadModel($id);
        $data = $this->getDataFormatted($this->getData($id));

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['site_administrator_group'])) {
            $modelGroup->attributes = $_POST['site_administrator_group'];
            $trans = Yii::app()->db->beginTransaction();
            if ($modelGroup->save()) {
                try {
                    $modelPrivilege = site_administrator_privilege::model()->find('administrator_privilege_administrator_group_id=' . $id);
                    if ($modelPrivilege != null) {
                        $modelPrivilege->deleteAll('administrator_privilege_administrator_group_id=' . $id);
                        if (isset($_POST['aksesparent'])) {

                            foreach ($_POST['aksesparent'] as $val => $value) {
                                $modelInsertPrivilege = new site_administrator_privilege;
                                $modelInsertPrivilege->administrator_privilege_administrator_group_id = $id;
                                $modelInsertPrivilege->administrator_privilege_administrator_menu_id = $value;
                                $modelInsertPrivilege->administrator_privilege_action_create = 0;
                                $modelInsertPrivilege->administrator_privilege_action_update = 0;
                                $modelInsertPrivilege->administrator_privilege_action_delete = 0;
                                $modelInsertPrivilege->save();
                            }
                            $modelInsertPrivilege->refresh();

                            if (isset($_POST['akseschild'])) {

                                foreach ($_POST['akseschild'] as $valchild => $valuechild) {
                                    $modelInsertPrivilegeChild = new site_administrator_privilege;
                                    $modelInsertPrivilegeChild->administrator_privilege_administrator_group_id = $id;
                                    $modelInsertPrivilegeChild->administrator_privilege_administrator_menu_id = $valuechild;
                                    $modelInsertPrivilegeChild->administrator_privilege_action_create = (isset($_POST['akseschild_create'][$valchild]) ? '1' : '0');
                                    $modelInsertPrivilegeChild->administrator_privilege_action_update = (isset($_POST['akseschild_update'][$valchild]) ? '1' : '0');
                                    $modelInsertPrivilegeChild->administrator_privilege_action_delete = (isset($_POST['akseschild_delete'][$valchild]) ? '1' : '0');

                                    $modelInsertPrivilegeChild->save();
                                }
                                $modelInsertPrivilegeChild->refresh();
                            }
                        }
                    }

                    $trans->commit();
                    $this->refresh();
                } catch (Exception $e) {
                    $trans->rollBack();
                }
            }
        }

        $this->render('update', array(
            'model' => $modelGroup,
            'data' => $data,
        ));
    }

    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            try {
                $this->loadModel($id)->delete();
                if (!isset($_GET['ajax'])) {
                    Yii::app()->user->setFlash('success', 'Hapus data berhasil');
                } else {
                    echo "<div class='flash-success'>Hapus data berhasil</div>";
                }
            } catch (CDbException $e) {
                if (!isset($_GET['ajax'])) {
                    Yii::app()->user->setFlash('error', "Hapus data gagal.<br/>Group <strong>" .
                            $this->loadModel($id)->administrator_group_title . "</strong> masih digunakan.");
                } else {
                    echo "<div class='flash-error'>Hapus data gagal.<br/>Group <strong>" .
                    $this->loadModel($id)->administrator_group_title . "</strong> masih digunakan.</div>"; //for ajax}
                }
                // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
                if (!isset($_GET['ajax'])) {
                    $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('list'));
                }
            }
        }
    }

    public function actionNonaktifkan() {
        $id = $_POST['id'];
        if ($id != 0 && $id != "") {
            $model = site_administrator_group::model()->findByPk((int) $id);
            $model->administrator_group_is_active = 0;
            if ($model->save()) {
                Yii::app()->user->setFlash('pesan', "Data berhasil di non aktifkan.");
                $return['msg'] = 'sukses';
            } else {
                Yii::app()->user->setFlash('pesan', "Data gagal di non aktifkan.");
                $return['msg'] = 'gagal';
            }
            echo json_encode($return);
        }
    }

    public function actionAktifkan() {
        $id = $_POST['id'];
        if ($id != 0 && $id != "") {
            $model = site_administrator_group::model()->findByPk((int) $id);
            $model->administrator_group_is_active = 1;
            if ($model->save()) {
                Yii::app()->user->setFlash('pesan', "Data berhasil diaktifkan.");
                $return['msg'] = 'sukses';
            } else {
                Yii::app()->user->setFlash('pesan', "Data gagal diaktifkan.");
                $return['msg'] = 'gagal';
            }
            echo json_encode($return);
        }
    }

    protected function loadModel($id) {
        $model = site_administrator_group::model()->findByPk((int) $id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /*
     * Proses menampilkan Tree
     */

    public function actionTreeFill() {
        if (!isset($_GET['root']))
            $personId = 'source';
        else
            $personId = $_GET['root'];

        $persons = ($personId == 'source') ?
                $this->getData() : $this->recursiveSearch($personId, $this->getData());

        $dataTree = array();
        if (is_array($persons)) {
            foreach ($persons as $parent)
                $dataTree[] = $this->formatData($parent);
        }
        echo json_encode($dataTree);
//        echo CTreeView::saveDataAsJson($dataTree);
    }

    protected function recursiveSearch($id, $rootnode) {
        if (is_array($rootnode)) {
            foreach ($rootnode as $person) {
                if ($person['id'] == $id)
                    return $person["parents"];
                else {
                    $r = $this->recursiveSearch($id, $person["parents"]);
                    if ($r !== null)
                        return $r;
                }
            }
        }
        return null;
    }

    protected function formatData($person) {
        return array(
            'text' => $person['name'],
            'id' => $person['id'],
            'hasChildren' => isset($person['parents']));
    }

    protected function getDataFormatted($data) {
        $personFormatted = null;
        foreach ($data as $k => $person) {
            $personFormatted[$k] = $this->formatData($person);
            $parents = null;
            if (isset($person['parents'])) {
                $parents = $this->getDataFormatted($person['parents']);
                $personFormatted[$k]['children'] = $parents;
            }
        }
        return $personFormatted;
    }

    protected function getData($administrator_privilege_administrator_group_id = 0) {
        $menu = site_administrator_menu::model()->findAll("administrator_menu_par_id=0");
        //$dataMenu = array();

        $datas = array(
            array("id" => 1, "name" => CHtml::checkbox("all", false) . '<strong> Centang Semua</strong>',
                "parents" => array()
            )
        );
        $menuParents = array();
        $menuChild = array();
        $i = 0;
        $checkParents = false;
        $checkChild = false;
        foreach ($menu as $val) {
            $privilegeParents = site_administrator_privilege::model()->find('administrator_privilege_administrator_menu_id=' . $val->administrator_menu_id . ' AND administrator_privilege_administrator_group_id=' . $administrator_privilege_administrator_group_id);
            if ($privilegeParents == null) {
                $checkParents = false;
            } else {
                $checkParents = true;
            }
            $menuItem = site_administrator_menu::model()->findAll("administrator_menu_par_id=" . $val->administrator_menu_id);
            //$dataMenu[$val->administrator_menu_id] = $val->attributes;
            $menuParents['id'] = $val->administrator_menu_id;
            $menuParents['name'] = CHtml::checkbox("aksesparent[" . $val->administrator_menu_id . "]", $checkParents, array('value' => $val->administrator_menu_id, 'class' => 'parentCls parent' . $val->administrator_menu_id)) . ' ' . $val->administrator_menu_title;
            $menuParents['parents'] = array();

            foreach ($menuItem as $item) {

                /*
                 * MENU ACTION
                 * 
                 */
                $privilegeChildCreate = site_administrator_privilege::model()->find('administrator_privilege_administrator_menu_id=' . $item->administrator_menu_id . ' AND administrator_privilege_administrator_group_id=' . $administrator_privilege_administrator_group_id . " AND administrator_privilege_action_create='1'");
                if ($privilegeChildCreate == null) {
                    $checkChildCreate = false;
                } else {
                    $checkChildCreate = true;
                }

                $menuCreate = ($item->administrator_menu_action_create == '0') ? '' : CHtml::checkbox("akseschild_create[" . $item->administrator_menu_id . "]", $checkChildCreate, array('value' => $item->administrator_menu_action_create, 'class' => 'childClsCreate child_action' . $val->administrator_menu_id)) . ' ' . 'Create';

                $privilegeChildUpdate = site_administrator_privilege::model()->find('administrator_privilege_administrator_menu_id=' . $item->administrator_menu_id . ' AND administrator_privilege_administrator_group_id=' . $administrator_privilege_administrator_group_id . " AND administrator_privilege_action_update='1'");
                if ($privilegeChildUpdate == null) {
                    $checkChildUpdate = false;
                } else {
                    $checkChildUpdate = true;
                }

                $menuUpdate = ($item->administrator_menu_action_update == '0') ? '' : CHtml::checkbox("akseschild_update[" . $item->administrator_menu_id . "]", $checkChildUpdate, array('value' => $item->administrator_menu_action_update, 'class' => 'childClsUpdate child_action' . $val->administrator_menu_id)) . ' ' . 'Update';

                $privilegeChildDelete = site_administrator_privilege::model()->find('administrator_privilege_administrator_menu_id=' . $item->administrator_menu_id . ' AND administrator_privilege_administrator_group_id=' . $administrator_privilege_administrator_group_id . " AND administrator_privilege_action_delete='1'");
                if ($privilegeChildDelete == null) {
                    $checkChildDelete = false;
                } else {
                    $checkChildDelete = true;
                }
                $menuDelete = ($item->administrator_menu_action_delete == '0') ? '' : CHtml::checkbox("akseschild_delete[" . $item->administrator_menu_id . "]", $checkChildDelete, array('value' => $item->administrator_menu_action_delete, 'class' => 'childClsDelete child_action' . $val->administrator_menu_id)) . ' ' . 'Delete';

                /*
                 * END MENU ACTION
                 */

                $privilegeChild = site_administrator_privilege::model()->find('administrator_privilege_administrator_menu_id=' . $item->administrator_menu_id . ' AND administrator_privilege_administrator_group_id=' . $administrator_privilege_administrator_group_id);
                if ($privilegeChild == null) {
                    $checkChild = false;
                } else {
                    $checkChild = true;
                }//$val->administrator_menu_id
                $menuChild['id'] = $item->administrator_menu_id;
                $menuChild['name'] = CHtml::checkbox("akseschild[" . $item->administrator_menu_id . "]", $checkChild, array('value' => $item->administrator_menu_id, 'class' => 'childCls child' . $val->administrator_menu_id)) . ' ' . $item->administrator_menu_title . ' ' . $menuCreate . ' ' . $menuUpdate . ' ' . $menuDelete . ' ' . $menuApproval;
                $menuChild['parents'] = array();
                
                

                $menuItem2 = site_administrator_menu::model()->findAll("administrator_menu_par_id=" . $item->administrator_menu_id);
                foreach ($menuItem2 as $item2) {
                    /*
                     * MENU ACTION
                     * 
                     */
                    $privilegeChildCreate = site_administrator_privilege::model()->find('administrator_privilege_administrator_menu_id=' . $item2->administrator_menu_id . ' AND administrator_privilege_administrator_group_id=' . $administrator_privilege_administrator_group_id . " AND administrator_privilege_action_create='1'");
                    if ($privilegeChildCreate == null) {
                        $checkChildCreate = false;
                    } else {
                        $checkChildCreate = true;
                    }

                    $menuCreate = ($item->administrator_menu_action_create == '0') ? '' : CHtml::checkbox("akseschild_create[" . $item2->administrator_menu_id . "]", $checkChildCreate, array('value' => $item2->administrator_menu_action_create, 'class' => 'childClsCreate child_action' . $item2->administrator_menu_id)) . ' ' . 'Create';

                    $privilegeChildUpdate = site_administrator_privilege::model()->find('administrator_privilege_administrator_menu_id=' . $item2->administrator_menu_id . ' AND administrator_privilege_administrator_group_id=' . $administrator_privilege_administrator_group_id . " AND administrator_privilege_action_update='1'");
                    if ($privilegeChildUpdate == null) {
                        $checkChildUpdate = false;
                    } else {
                        $checkChildUpdate = true;
                    }

                    $menuUpdate = ($item->administrator_menu_action_update == '0') ? '' : CHtml::checkbox("akseschild_update[" . $item2->administrator_menu_id . "]", $checkChildUpdate, array('value' => $item2->administrator_menu_action_update, 'class' => 'childClsUpdate child_action' . $item2->administrator_menu_id)) . ' ' . 'Update';

                    $privilegeChildDelete = site_administrator_privilege::model()->find('administrator_privilege_administrator_menu_id=' . $item2->administrator_menu_id . ' AND administrator_privilege_administrator_group_id=' . $administrator_privilege_administrator_group_id . " AND administrator_privilege_action_delete='1'");
                    if ($privilegeChildDelete == null) {
                        $checkChildDelete = false;
                    } else {
                        $checkChildDelete = true;
                    }
                    $menuDelete = ($item->administrator_menu_action_delete == '0') ? '' : CHtml::checkbox("akseschild_delete[" . $item2->administrator_menu_id . "]", $checkChildDelete, array('value' => $item2->administrator_menu_action_delete, 'class' => 'childClsDelete child_action' . $item2->administrator_menu_id)) . ' ' . 'Delete';

                    /*
                     * END MENU ACTION
                     */

                    $privilegeChild = site_administrator_privilege::model()->find('administrator_privilege_administrator_menu_id=' . $item2->administrator_menu_id . ' AND administrator_privilege_administrator_group_id=' . $administrator_privilege_administrator_group_id);
                    if ($privilegeChild == null) {
                        $checkChild = false;
                    } else {
                        $checkChild = true;
                    }//$val->administrator_menu_id
                    $menuChild2['id'] = $item2->administrator_menu_id;
                    $menuChild2['name'] = CHtml::checkbox("akseschild[" . $item2->administrator_menu_id . "]", $checkChild, array('value' => $item2->administrator_menu_id, 'class' => 'childCls child' . $item->administrator_menu_id)) . ' ' . $item2->administrator_menu_title . ' ' . $menuCreate . ' ' . $menuUpdate . ' ' . $menuDelete . ' ' . $menuApproval;
                    array_push($menuChild['parents'], $menuChild2);
                }
                array_push($menuParents['parents'], $menuChild);
            }
            
            array_push($datas[0]['parents'], $menuParents);
            $i++;
        }
        //echo "<pre>";
       // var_dump($datas);
        return $datas;
        
    }

    public function getDataCity() {
        $results = RefRegion::model()->findAll('region_par_id!=0');
        $data = array();
        foreach ($results as $result) {
            $data[$result->region_id] = $result->region_name;
        }
        return $data;
    }

    /*
     * Akhir proses menampilkan Tree
     */
}